package com.baturu.vin.dfpv;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author: chenjiahao
 * @Time: 2019/4/4
 */
@Slf4j
public class ListMapTransformers{

    public static <T> List<T> mapConvertToBean(List<Map<String, String>> input,Class<T> claszz) {
        return input.stream().map(d -> {
            T v = null;
            try {
                BeanInfo beanInfo = Introspector.getBeanInfo(claszz);
                PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
                if (ArrayUtils.isEmpty(propertyDescriptors)) {
                    log.warn("{}包含的属性为空", claszz.getSimpleName());
                    return null;
                }
                v = claszz.newInstance();
                for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                    String name = propertyDescriptor.getName();
                    if ("class".equals(name)) {
                        continue;
                    }
                    propertyDescriptor.getWriteMethod().invoke(v, d.getOrDefault(propertyDescriptor.getName(), ""));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return v;
        }).filter(Objects::nonNull).collect(Collectors.toList());
    }
}
